<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="商品名称">
							<uni-easyinput v-model="searchModel.productName" placeholder="请输入商品名称" />
						</uni-forms-item>
						<uni-forms-item label="供应商">
							<uni-easyinput v-model="searchModel.supplierName" placeholder="请输入供应商" />
						</uni-forms-item>
						<uni-forms-item label="订单状态">
							<ty-data-select
								multiple
								v-model="searchModel.status"
								placeholder="请选择订单状态"
								:localdata="allStatusList"></ty-data-select>
						</uni-forms-item>
						<uni-forms-item label="开始时间">
							<uni-datetime-picker type="datetime" placeholder="请选择开始时间" v-model="searchModel.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间">
							<uni-datetime-picker type="datetime" placeholder="请选择结束时间" v-model="searchModel.endTime"/>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
		</up-popup>
		<view class="content">
			<!--操作-->
			<view class="operate main-flex">
				<view class="operate-item" v-if="checkPermi(['zhouyz:purchaseOrder:add'])">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="addFun">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">新增采购单</view>
					</up-button>
				</view>
			</view>
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					:selectedRowsKey="selectedRowsKey"
					@selection-change="selectRow"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					rowKey="productId"
					stripe
					border>
					<template v-slot:before="{ row }">
						<view class="table-td-before table-cell table-td-row">
							<view class="table-td-row">
								供应商：
								<text class="table-td-text">{{row.supplierName}}</text>
							</view>
							<view class="table-td-row">
								商品名称：
								<text class="table-td-text">{{row.productName}}</text>
							</view>
							<view class="table-td-row">
								商品单位：
								<text class="table-td-text">{{row.productUnit}}</text>
							</view>
						</view>
					</template>
					<template v-slot:left="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								销售数量：
								<text class="table-td-text">{{row.productCount || 0}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								销售金额：
								<text class="table-td-text red">{{row.productPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								当前售价：
								<text class="table-td-text red">{{row.currentSellPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								平均售价：
								<text class="table-td-text red">{{row.averageSellPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								毛利：
								<text class="table-td-text red">{{row.grossProfit}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								单品毛利：
								<text class="table-td-text red">{{row.averageGrossProfit}}</text>
							</view>
						</view>
					</template>
					<template v-slot:right="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								退货数量：
								<text class="table-td-text">{{row.refundCount || 0}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								退款金额：
								<text class="table-td-text red">{{row.refundPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								采购金额：
								<text class="table-td-text red">{{row.purchasePrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								当前采购价：
								<text class="table-td-text red">{{row.currentPurchasePrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								平均采购价：
								<text class="table-td-text red">{{row.averagePurchasePrice}}</text>
							</view>
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
				<view class="table-total" v-if="tableList.length > 0">
					<view class="table-total-title">合计：</view>
					<view class="table-cell main-flex">
						<view class="table-td-cell">
							<view class="table-td-row">
								销售数量：
								<text class="table-td-text">{{totalData.productCount}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								销售金额：
								<text class="table-td-text red">{{totalData.productPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								当前售价：
								<text class="table-td-text red">{{totalData.currentSellPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								平均售价：
								<text class="table-td-text red">{{totalData.averageSellPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								毛利：
								<text class="table-td-text red">{{totalData.grossProfit}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								单品毛利：
								<text class="table-td-text red">{{totalData.averageGrossProfit}}</text>
							</view>
						</view>
						
						<view class="table-td-cell">
							<view class="table-td-row">
								退货数量：
								<text class="table-td-text">{{totalData.refundCount}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								退款金额：
								<text class="table-td-text red">{{totalData.refundPrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								采购金额：
								<text class="table-td-text red">{{totalData.purchasePrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								当前采购价：
								<text class="table-td-text red">{{totalData.currentPurchasePrice}}</text>
							</view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:supplierProductSaleSummary:price'])">
								平均采购价：
								<text class="table-td-text red">{{totalData.averagePurchasePrice}}</text>
							</view>
						</view>
						
					</view>
				</view>
			</view>
			<!--统计图-->
			<!-- <view class="charts-box">
				<qiun-data-charts 
					type="column"
					:opts="opts"
					:chartData="chartData"
				/>
			</view> -->
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { allProvince } from "@/api/erp_api/region"
import { orderStatus } from "@/api/system/dict/data"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import qiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue'
import { warehouse } from "@/api/erp_api/warehouse"
import { supplierProductSaleSummary } from "@/api/erp_api/finance"
import { isObjectEmptySimple, copyText, arrText, getRecentDays } from '@/utils/ty.js'
import { sellChannelList } from '@/utils/config.js'
import { searchDefaultParams } from '@/utils/searchDefault.js'
import useUserStore from '@/store/modules/user'
import { Decimal } from 'decimal.js'
import useSetStore from '@/store/modules/set'

	const userStore = useUserStore()
	const setStore = useSetStore()

	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
	})
	
	// 获取订单状态
	const allStatusList = ref([])
	const getOrderStatus = () => {
		return orderStatus().then(res => {
			allStatusList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	// 获取仓库
	const allWarehouseList = ref([])
	const getWarehouse = () => {
		warehouse().then(res => {
			allWarehouseList.value = res.rows.map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		productName: '',
		startTime: ``,
		endTime: ``,
		supplierName: '',
		warehouseId: '',
		status: []
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			productName: '',
			startTime: ``,
			endTime: ``,
			supplierName: '',
			warehouseId: '',
			status: []
		}
		setParams()
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ type: 'selection', width: '80rpx' },
		{ title: '数量', key: 'left' },
		{ title: '金额', key: 'right' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.productName) {
			params.productName = searchModel.value.productName
		}
		if (searchModel.value.startTime) {
			params.startTime = searchModel.value.startTime
		}
		if (searchModel.value.endTime) {
			params.endTime = searchModel.value.endTime
		}
		if (searchModel.value.supplierName) {
			params.supplierName = searchModel.value.supplierName
		}
		if (searchModel.value.status && searchModel.value.status.length > 0) {
			params.status = searchModel.value.status
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		supplierProductSaleSummary(params).then(res => {
			tableList.value = res.data || []
			selectedRowsKey.value = []
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	const selectedRowsKey = ref([])
	const selectRow = (e) => {
		selectedRowsKey.value = e
	}
	// 合计
	const totalData = computed(() => {
		return {
			productCount: totalDataOne('productCount'),
			productPrice: totalDataOne('productPrice'),
			currentSellPrice: totalDataOne('currentSellPrice'),
			averageSellPrice: totalDataOne('averageSellPrice'),
			grossProfit: totalDataOne('grossProfit'),
			averageGrossProfit: totalDataOne('averageGrossProfit'),
			refundCount: totalDataOne('refundCount'),
			refundPrice: totalDataOne('refundPrice'),
			purchasePrice: totalDataOne('purchasePrice'),
			currentPurchasePrice: totalDataOne('currentPurchasePrice'),
			averagePurchasePrice: totalDataOne('averagePurchasePrice')
		}
	})
	
	const totalDataOne = (key) => {
		return tableList.value.reduce((prev, cur, index, arr)=> {
			return Decimal(prev).add(cur[key] ? cur[key] : 0).toNumber()
		}, 0)
	}
	
	const chartData = ref({})
	const opts = ref({
		color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
		padding: [15,15,0,5],
		touchMoveLimit: 24,
		legend: {},
		xAxis: {
			fontSize: 10,
			rotateLabel: true
		},
		yAxis: {
			data: [
				{
					min: 0
				}
			]
		},
		extra: {
			column: {
				type: "group",
				width: 10,
				activeBgColor: "#000000",
				activeBgOpacity: 0.08
			}
		}
	})
	
	// 新增采购单
	const addFun = () => {
		if (selectedRowsKey.value.length === 0) return uni.$u.toast('请选择商品')
		const supplierFilterId = selectedRowsKey.value[0].supplierId
		const supplierFilterArr = selectedRowsKey.value.filter(item => item.supplierId !== supplierFilterId)
		if (supplierFilterArr.length > 0) return uni.$u.toast('请选择同一供应商商品')
		const purchaseOrder =  {
			supplierId: supplierFilterId,
			productList: selectedRowsKey.value.map(item => {
				return {
					supplierId: item.supplierId,
					supplierName: item.supplierName,
					productId: item.productId,
					productName: item.productName,
					productUnit: item.productUnit,
					productCount: item.productCount
				}
			})
		}
		setStore.setPurchaseOrderList(purchaseOrder)
		uni.navigateTo({
			url: '/pages/purchase/purchaseOrderAdd'
		})
	}
	const setParams = () => {
		const params = searchDefaultParams('supplierProductSaleSummary')
		searchModel.value = {
			...searchModel.value,
			...params
		}
	}
	watch(() => userStore.roles, (nval, oval) => {
		if (nval && nval.length > 0) {
			setParams()
			searchFirst()
		}
	}, { immediate: true })
	onMounted(async () => {
		await getWarehouse()
		await getOrderStatus()
		searchFirst()
	})
</script>

<style scoped lang="scss">
	.charts-box {
		position: relative;
		width: 100%;
		height: 300px;
		background-color: #ffffff;
		z-index: 999;
	}
</style>
